package visualizer.input;

import java.awt.event.KeyEvent;
import java.util.List;

import processing.core.PGraphics;
import processing.core.PVector;

public class ComponentCollection extends Component {
	private List<Component> components;
	
	public ComponentCollection(PVector position, List<Component> components) {
		super(position, calculateDimensions(components));
		this.components = components;
	}
	
	private static PVector calculateDimensions(Iterable<Component> components)
	{
		float width = 0;
		float height = 0;
		
		for (Component c : components) {
			float requiredHorizontalSpace = c.getPosition().x + c.getSize().x;
			if (requiredHorizontalSpace > width) {
				width = requiredHorizontalSpace;
			}
			
			float requiredVerticalSpace = c.getPosition().y + c.getSize().y;
			if (requiredVerticalSpace > height) {
				height = requiredVerticalSpace;
			}
		}
		
		return new PVector(width, height);
	}

	protected void drawRelative(PGraphics g) {
		for (Component c : components) {
			c.draw(g);
		}
	}
	
	public void keyPressed(char key) {
		if (hasFocus()) {
			if (key == KeyEvent.VK_TAB) {
				cycleFocus();
			} else {
				for (Component c : components) {
					c.keyPressed(key);
				}
			}
		}
	}
	
	public void cycleFocus()
	{
		boolean focusNext = false;
		for (Component c : components) {
			if (c.hasFocus()) {
				focusNext = true;
				c.setFocus(false);
			} else {
				c.setFocus(focusNext);
				focusNext = false;
			}
		}
		if (focusNext) {
			components.get(0).setFocus(true);
		}
	}

	public void mouseMoved(PVector p) {
		super.mouseMoved(p);
		for (Component c : components) {
			c.mouseMoved(getRelativePosition(p));
		}
	}
	
	public void mousePressed(PVector p) {
		super.mousePressed(p);
		for (Component c : components) {
			c.mousePressed(getRelativePosition(p));
		}
	}
	
	public PVector getRelativePosition(PVector absolute)
	{
		return new PVector(absolute.x - getPosition().x, absolute.y - getPosition().y);
	}
}
